package com.example.leetcode.solution;

import com.example.leetcode.ListNode;

public class Solution24 {

    public static ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode temp = head;
        int index = 1;
        ListNode tail = null;
        while (temp != null && temp.next != null) {
            ListNode pre = temp;
            ListNode current = temp.next;
            ListNode next = null;
            if (current != null) {
                next = current.next;
            }
            temp = current;
            index++;
            if (index % 2 == 0) {
                if (index == 2) {
                    tail = pre;
                    pre.next = next;
                    current.next = pre;
                    temp = pre;
                    head = current;
                }else{
                    tail.next = current;
                    pre.next = next;
                    current.next = pre;
                    temp = pre;
                    tail = pre;
                }
            }
        }
        return head;
    }
}
